const noteTable = require('../models/noteTable');
const inspirecloud = require('@byteinspire/inspirecloud-api');
const ObjectId = inspirecloud.db.ObjectId;


class NoteService {
    /**
     * 列出所有的笔记记录
     */
    async listAll() {
        return await noteTable.where({is_delete: false}).sort({createAt: -1}).find();
    }

    /**
     * 列出分页内的笔记记录
     */
    async queryById(params) {
        let {page, pageNum, info_id} = params;
        let queryParams = {is_delete: false};
        if (info_id !== undefined && info_id.trim() !== '') {
            queryParams.info_id = info_id;
        }
        let result = await noteTable.where(queryParams).count();
        let list = await noteTable.where(queryParams)
        .skip((page - 1) * pageNum)
        .limit(pageNum)
        .sort({createAt: -1}).find();
        let data = {note:list,total:result};
        return data;
    }

    /**
     * 根据id查找记录
     */
    async getOneById(id) {
        return await noteTable.where({_id: ObjectId(id)}).findOne();
    }

    /**
     * 根据info_id查找记录
     */
     async getByInfoId(info_id) {
        return await noteTable.where({info_id: ObjectId(info_id)}).find();
    }

    /**
     * 创建一条账单事项
     * @param Note 用于创建账单事项的数据，原样存进数据库
     * @return {Promise<any>} 返回实际插入数据库的数据，会增加_id，createdAt和updatedAt字段
     */
    async create(Note) {
        return await noteTable.save(Note);
    }

    /**
     * 删除一条笔记
     * @param id 笔记的 _id
     * 若不存在，则抛出 404 错误
     */
    async delete(id) {
        const Note = await noteTable.where({_id: ObjectId(id)}).findOne();
        if (!Note) {
            const error = new Error(`note:${id} not found`);
            error.status = 404;
            throw error;
        }
        Note.is_delete = true;
        await noteTable.save(Note);
    }


    /**
     * 更新一条笔记
     * @param newNote._id 将会用原对象 merge 此对象进行更新
     * 若不存在，则抛出 404 错误
     */
    async update(newNote) {
        const Note = await noteTable.where({_id: ObjectId(newNote._id)}).findOne();
        if (!Note) {
            const error = new Error(`Note:${newNote._id} not found`);
            error.status = 404;
            throw error;
        }
        Object.assign(Note, newNote);
        Note._id=ObjectId(Note._id)
        await noteTable.save(Note);
    }
}

// 导出 Service 的实例
module.exports = new NoteService();